package com.zoffy.apiclientsdk.client;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 调用第三方接口的api
 *
 * @author zoffy
 */
@Slf4j
public class ZoffyApiClient {
    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    private  String accessKey;
    private  String secretKey;
    private String interfaceId;
    private final String GATEWAY_URL="http://localhost:9800?";
    public ZoffyApiClient(String accessKey,String secretKey,String interfaceId){
        this.accessKey=accessKey;
        this.secretKey=secretKey;
        this.interfaceId=interfaceId;
    }
    public void setInterfaceId(String interfaceId){
        this.interfaceId=interfaceId;
    }

    public String get(HashMap<String,String> queryParams){
        StringBuilder url=new StringBuilder(GATEWAY_URL);
        for (Map.Entry<String,String> entry:queryParams.entrySet()) {
            String temp=entry.getKey()+"="+entry.getValue()+"&";
            url.append(temp);
        }
        String targetUrl=url.toString();
        String result = HttpRequest.get(targetUrl).addHeaders(genSignature()).execute().body();
        log.info(String.format("请求方式: GET,请求结果: %s", result));
        return result;
    }
    public String post(HashMap paramMap){
        String json = JSONUtil.toJsonStr(paramMap);
        String result = HttpRequest.post(GATEWAY_URL)
                .addHeaders(genSignature())
                .body(json)
                .execute().body();
        log.info(String.format("请求方式: POST,请求结果: %s", result));
        return result;
    }
    public HashMap<String,String> genSignature(){
        //生成签名
        String nanos = RandomUtil.randomNumbers(100);
        String timestamp = String.valueOf(System.currentTimeMillis() / 100);
        String signature = DigestUtil.sha256Hex(accessKey + timestamp + nanos + secretKey);
        //将验证参数封装到hashMap中并转未为json
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("accessKey",accessKey);
        hashMap.put("nanos",nanos);
        hashMap.put("interfaceId",String.valueOf(interfaceId));
        hashMap.put("timestamp",timestamp);
        hashMap.put("signature",signature);

        String json = JSONUtil.toJsonStr(hashMap);
        //将json数据进行base64编码作为最终生成的签名
        HashMap<String,String> headers=new HashMap<>();
        headers.put("signature",Base64.encode(json));
        return headers;
    }
}
